var xslDoc;
var xmlDoc;
var xmlHttpObj;
var sortingField = "Name";
var sortOrder = "ascending";
var sortType = "text";

function CreateXmlHttpRequestObject()
{
    var xmlObj;
	
    if (window.ActiveXObject) {
		alert('Sorry, old browsers are not supported!\nTo run the project open the .xsl file, uncomment first lines and then open the .xml file!');
		window.stop();
    } else {
        xmlObj = new XMLHttpRequest();
    }
	
    return xmlObj;
}

function getStyleSheet()
{
    xmlHttpObj = CreateXmlHttpRequestObject();
	try {
		xmlHttpObj.open('GET', 'XSLT-companies-tranformation.xsl', false);
		xmlHttpObj.send(null);
	} catch (e) {
		alert('You must fix your browser\'s security settings!\nTry with Firefox.\nFor Chrome --disable-web-security.\nTo run the project open the .xsl file, uncomment first lines and then open the .xml file!');
	}
    if (xmlHttpObj.status == 200 || xmlHttpObj.status == 0) {
        xslDoc = xmlHttpObj.responseXML; 
    } else {
        alert('error loading stylesheet ' + xmlHttpObj.status);
    }
}

function getDataFile()
{
    xmlHttpObj = CreateXmlHttpRequestObject();    
    xmlHttpObj.open('GET', 'companies.xml', false);
    xmlHttpObj.send(null);
    if (xmlHttpObj.status == 200 || xmlHttpObj.status == 0) {
        xmlDoc = xmlHttpObj.responseXML;
    } else {
        alert('error loading data file ' + xmlHttpObj.status);
    }
}

function doTranslation()
{
    try {
        getStyleSheet();
        getDataFile();
        var processor = new XSLTProcessor();
        processor.importStylesheet(xslDoc);
        processor.setParameter(null, "sortingField", sortingField);
        processor.setParameter(null, "sortOrder", sortOrder);
        processor.setParameter(null, "sortType", sortType);
        var newDocument = processor.transformToDocument(xmlDoc);
        document.getElementById("container-companies").innerHTML = new XMLSerializer().serializeToString(newDocument);
        document.getElementById("slides").innerHTML = "";
    } catch (e) {
        alert('error translating data file');
    }
}

function sortBy(fieldToSort)
{
    if (sortingField == fieldToSort) {
        sortOrder = (sortOrder == 'ascending') ? 'descending' : 'ascending';
    } else {
        sortingField = fieldToSort;
        sortOrder = 'ascending';
    }
    sortType = (sortingField === "Employees" || sortingField === "Revenue") ? "number" : "text";

    doTranslation();
}
